package com.cloud.advice;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;

import com.cloud.dto.ResponseDto;
import com.cloud.exception.BusinessException;

@ControllerAdvice
@Slf4j
public class ExceptionHandlerAdvice {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseDto exception(Exception e, WebRequest request) {
        ResponseDto responseDto = new ResponseDto();
        if (e instanceof BusinessException) {
            responseDto.setCode(((BusinessException) e).getCode());
            responseDto.setMsg(e.getMessage());
        } else {
            // 后台未定义异常统一code为100
            responseDto.setCode(100);
            responseDto.setMsg(e.getMessage());
        }
        log.error("后台异常信息：", e);
        return responseDto;
    }
}
